import time
import requests
import random
import os
import json

from secware.api import get_theme_ids, get_headers, get_img_task_info, submit_img_task_answer, get_user_info


# 保存token
def write_credentials_to_file(num, user_address, token):
    # 创建文件
    if not os.path.exists(f"D:/chromeFile/goplus_token"):
        os.makedirs(f"D:/chromeFile/goplus_token")
    file_name = f"D:/chromeFile/goplus_token/{num}.json"
    credentials = {user_address: token}
    with open(file_name, 'w') as file:
        json.dump(credentials, file)


# 读取token
def get_credentials(num):
    file_name = f"D:/chromeFile/goplus_token/{num}.json"
    # 判断文件是否存在
    if os.path.exists(file_name):
        with open(file_name, 'r') as file:
            data = json.load(file)
            user_address = list(data.keys())[0]
            token = data[user_address]
        return token, user_address
    return None, None


# 判断token 是否有效
def is_valid_token(num):
    token, user_address = get_credentials(num)
    print("token:", token, "user_address:", user_address)
    if token and user_address:
        return get_user_info(token, user_address)
    return False


def fetch_and_process_tasks(token, user_address, filter_task, opt_id_map):
    theme_id_list = get_theme_ids(token, user_address)
    for theme_id in theme_id_list:
        time.sleep(2)
        url = f"https://api.secwarex.io/api/v1/task/required/list?chainId=1&themeId={theme_id}&userAddress={user_address}"
        headers = get_headers(token, user_address)
        response = requests.get(url, headers=headers, verify=False)
        if response.status_code == 200:
            data = response.json()
            results = data.get("result", [])
            for result in results:
                task_id = result.get("taskId")
                if filter_task.count(task_id) > 0:
                    continue
                status = result.get("status")
                if status == 'FINISH':
                    print(f"task_id:{task_id} 已经完成")
                    continue
                print("Theme ID:", theme_id)
                print("Task ID:", task_id)
                print("Starting task details retrieval")
                task_info = get_img_task_info(task_id, theme_id, token, user_address)
                if task_info:
                    opt_id = opt_id_map.get(task_id)
                    if opt_id is None:
                        print(f"task_id:{task_id} 找不到答案")
                    print(result)
                    final_result = submit_img_task_answer(task_id, theme_id, opt_id, token)
                    print(final_result)
                    random_number = random.randint(10, 20)
                    time.sleep(random_number)
        else:
            print("Failed to fetch data. Status code:", response.status_code)


def get_opt_id_map():
    return {
        156: 208,
        155: 205,
        140: 181,
        141: 184,
        139: 178,
        153: 199,
        154: 202,
        148: 187,
        149: 192,
        151: 194,
        152: 196,
        157: 211,
        158: 214
    }


def get_filter_task():
    return [147, 142, 145, 146, 143, 150]


def start_task(num):
    time.sleep(5)
    opt_id_map = get_opt_id_map()
    filter_task = get_filter_task()
    # 获取token
    token, user_address = get_credentials(num)
    try:
        if token and user_address:
            fetch_and_process_tasks(token, user_address, filter_task, opt_id_map)
            print(f"浏览器 {num} 执行完成")
        else:
            print(f"浏览器 {num} token 无效")
    except Exception as e:
        print(f"浏览器 {num} 异常", e)


def doplus_task(num):
    start_task(num)
